<?php

namespace app\libs\PaypalSDK\builder;

use app\model\Orders;
use think\helper\Arr;
use think\Request;

class QuickPayBuilder
{
    private string $currencyCode;
    private string $returnUrl;
    public function __construct(protected Request $request)
    {
        $checkout = $this->request->param('checkout',[]);
        $this->currencyCode = Arr::get($checkout,'cart.currency','USD');
    }

    public function toArray()
    {
        return [
            'intent'=>'CAPTURE',
            'purchase_units'=>$this->getTransactions(),
            'application_context'=>$this->get_application_context(),
        ];
    }

    private function getTransactions(): array
    {
        list($lines, $subtotal_price) = $this->getItemLines();
        list($total_money,$tax_price) = Orders::calculateTotalPrice($subtotal_price);
        $breakDown = [
            'item_total'=>['value'=>$subtotal_price, 'currency_code'=>$this->currencyCode,],
        ];

        if($tax_price > 0){
            $breakDown['tax_total'] = ['value'=>$tax_price,'currency_code'=>$this->currencyCode];
        }
        return [
            [
                'amount'=>[
                    'value'=>$total_money,
                    'currency_code'=>$this->currencyCode,
                    'breakdown'=>$breakDown,
                ],
                'items'=>$lines,
            ]
        ];
    }

    private function get_application_context():array
    {

        return [
            'return_url'=>$this->getReturnUrl(),
            'cancel_url'=>$this->request->header('referer'),
        ];

    }

    private function getItemLines(): array
    {
        $checkout = $this->request->param('checkout',[]);
        $items = Arr::get($checkout,'cart.items',[]);
        $lines = [];
        $subtotal_price = '0.00';

        foreach ($items as $item){
            $price = Arr::get($item,'presentment_price',0);
            $quantity = Arr::get($item,'quantity',1);
            $lines[] = [
                'name' => mb_substr(Arr::get($item,'title', ''),0, 120),
                'description' =>Arr::get($item,'variant_title',''),
                'quantity' => $quantity,
                'unit_amount' => ['value' => $price, 'currency_code' => $this->currencyCode],
                'sku'=>Arr::get($item,'sku','') ?: Arr::get($item,'id',''),
            ];
            $sub_price = bcmul($price,(string)$quantity,2);
            $subtotal_price = bcadd($sub_price,$subtotal_price,2);
        }
        return [$lines,$subtotal_price];
    }

    public function getReturnUrl(): string
    {
        return $this->returnUrl;
    }

    public function setReturnUrl(string $returnUrl): void
    {
        $this->returnUrl = $returnUrl;
    }

}